package com.itcast.googleplay.fragment;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RelativeLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.itcast.googleplay.DetailActivity;
import com.itcast.googleplay.R;
import com.itcast.googleplay.adapter.MyBaseAdapter;
import com.itcast.googleplay.adapter.MyPagerAdapter;
import com.itcast.googleplay.bean.AppInfo;
import com.itcast.googleplay.bean.Home;
import com.itcast.googleplay.holder.BaseHolder;
import com.itcast.googleplay.holder.HomeHolder;
import com.itcast.googleplay.protocol.HomeProtocal;
import com.itcast.googleplay.ui.LoadingPage.ResultState;
import com.itcast.googleplay.utils.UIUtils;

public class HomeFragment extends BaseFragment {

	private PullToRefreshListView pullToRefreshListView;
	private ListView listView;
	private Home homeData;
	private MyAdapter myAdapter;
	private LinearLayout llContainer;
	private ViewPager viewPager;
	private RunnableTask runnableTask;
	private List<BaseHolder> holderList = new ArrayList<BaseHolder>();
	
	@Override
	public ResultState onSubLoad() {
		HomeProtocal homeProtocal = new HomeProtocal();
		homeData = homeProtocal.getData("home", 0, "");
		if(homeData!=null){
			return ResultState.STATE_SUCCESSED;
		}
		return ResultState.STATE_ERROR;
	}

	@Override
	public View onCreateSuccessedSubView() {
		pullToRefreshListView = (PullToRefreshListView) UIUtils.inflate(R.layout.layout_refresh_list);
		listView = pullToRefreshListView.getRefreshableView();
		
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				Intent intent = new Intent(UIUtils.getContext(),DetailActivity.class);
				intent.putExtra("packagename",homeData.list.get(position-2).packageName);
				startActivity(intent);
			}
		});
		
		initData();
		
		View view = UIUtils.inflate(R.layout.layout_header_view);
		listView.addHeaderView(view);
		listView.setDivider(null);
		
		llContainer = (LinearLayout) view.findViewById(R.id.ll_container);
		
		for(int i=0;i<homeData.picture.size();i++){
			ImageView imageView = new ImageView(UIUtils.getContext());
			if(i == 0){
				//i为0时点设置为白色,选中颜色
				imageView.setBackgroundResource(R.drawable.indicator_selected);
			}else{
				//i为0时点设置为黑色,未选中颜色
				imageView.setBackgroundResource(R.drawable.indicator_normal);
			}
			LayoutParams layoutParams = new LinearLayout.LayoutParams
				(LinearLayout.LayoutParams.WRAP_CONTENT, 
				LinearLayout.LayoutParams.WRAP_CONTENT);
			layoutParams.rightMargin = UIUtils.dip2px(5);
			layoutParams.bottomMargin = UIUtils.dip2px(5);
			
			llContainer.addView(imageView,layoutParams);
		}
		
		
		viewPager = (ViewPager) view.findViewById(R.id.viewpager);
		viewPager.setAdapter(new MyPagerAdapter(homeData.picture));
		
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				int size = homeData.picture.size();
				for(int i=0;i<homeData.picture.size();i++){
					if(position%size == i){
						llContainer.getChildAt(position%size).setBackgroundResource(R.drawable.indicator_selected);
					}else{
						llContainer.getChildAt(i).setBackgroundResource(R.drawable.indicator_normal);
					}
				}
			}
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}
			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});
		
		startScroll();
		
		RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) viewPager.getLayoutParams();
		int width = getActivity().getWindowManager().getDefaultDisplay().getWidth();
		int height = (int) (width/2.65+0.5f);
		layoutParams.height = height;
		layoutParams.width = width;
		viewPager.setLayoutParams(layoutParams);
		
		pullToRefreshListView.setMode(Mode.BOTH);
		pullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				refreshOrLoadMore();
			}
		});
		return pullToRefreshListView;
	}


	private void startScroll() {
		UIUtils.getHandler().removeCallbacksAndMessages(null);
		
		runnableTask = new RunnableTask();
		runnableTask.start();
	}
	
	class RunnableTask implements Runnable{
		public void start() {
			//开启任务,2秒钟执行此任务的run方法
			UIUtils.getHandler().postDelayed(this, 2000);
		}
		@Override
		public void run() {
			int currentItem = viewPager.getCurrentItem();
			viewPager.setCurrentItem(++currentItem);
			
			UIUtils.getHandler().removeCallbacks(this);
			UIUtils.getHandler().postDelayed(this, 2000);
		}
	}
	
	@Override
	public void onStop() {
		if(runnableTask!=null){
			UIUtils.getHandler().removeCallbacks(runnableTask);
		}
		super.onStop();
	}
	
	@Override
	public void onDestroy() {
		if(runnableTask!=null){
			UIUtils.getHandler().removeCallbacks(runnableTask);
			for (int i = 0; i < holderList.size(); i++) {
				HomeHolder holder = (HomeHolder) holderList.get(i);
				holder.cancelDownload();
			}
		}
		super.onDestroy();
	}
	
	private void initData() {
		myAdapter = new MyAdapter(homeData.list);
		listView.setAdapter(myAdapter);
	}

	protected void refreshOrLoadMore() {
		if(pullToRefreshListView.getCurrentMode() == Mode.PULL_FROM_START){
			homeData.list.clear();
			showData();
			pullToRefreshListView.onRefreshComplete();
		}else{
			new Thread(){
				public void run() {
					HomeProtocal homeProtocal = new HomeProtocal();
					final Home moreData = homeProtocal.getData("home", homeData.list.size(), "");
					UIUtils.runInMainThread(new Runnable() {
						@Override
						public void run() {
							if(moreData.list.size()>0){
								homeData.list.addAll(moreData.list);
								myAdapter.notifyDataSetChanged();
								pullToRefreshListView.onRefreshComplete();
							}
						}
					});
				};
			}.start();
		}
	}
	
	class MyAdapter extends MyBaseAdapter<AppInfo>{
		public MyAdapter(List<AppInfo> list) {
			super(list);
		}

		@Override
		public BaseHolder<AppInfo> getHolder() {
			HomeHolder homeHolder = new HomeHolder();
			holderList.add(homeHolder);
			return homeHolder;
		}
	}
	
	@Override
	public void onResume() {
		if(myAdapter!=null){
			myAdapter.notifyDataSetChanged();
		}
		super.onResume();
	}
}
